//
//  ICCreateGroupManager.m
//  ICome
//
//  Created by zhangrongwu on 2017/8/17.
//  Copyright © 2017年 iCom. All rights reserved.
//

#import "ICCreateGroupManager.h"
#import "ICGroupUser.h"
#import "ICHeaderFile.h"
@implementation ICCreateGroupManager
+(NSDictionary *)createMultGroupParamWithUserList:(NSArray *)list {
    
    NSMutableArray *eIdList = [[NSMutableArray alloc] init];
    NSMutableArray *eNameList = [[NSMutableArray alloc] init];
    
    NSInteger Limt = 2;
    for (int index = 0; index < list.count; index++) {
        ICEmpInfoModel *model = [list objectAtIndex:index];
        if (model.select) {
            [eIdList addObject:model.eId];
            if (Limt != 0) {
                [eNameList addObject:model.eName];
                Limt--;
            }
        }
    }
    
    NSMutableString *gNameMutable = [[NSMutableString alloc] initWithString:[eNameList componentsJoinedByString:@"、"]];
    if (eIdList.count > 1) {
        for (ICEmpInfoModel *model in list) {
            if ([model.eId isEqualToString:[ICUser currentUser].eId]) {
                [eIdList removeObject:[ICUser currentUser].eId];
            }
        }
        if (eIdList.count >= 3) {
            [gNameMutable appendString:@"等"];
        }
    }
    NSString *gName = [gNameMutable copy];
    NSDictionary *dic = @{@"eId":[ICUser currentUser].eId,
                          @"eName":[ICUser currentUser].eName,
                          @"gName":gName,
                          @"eIds":eIdList};
    return dic;
}


+ (void)createMultGroupWith:(NSDictionary *)param Handle:(CreateSuccessHandle)handle {

    [[ICSocketRequestManager sharedInstance] multGroupWithObject:param Success:^(id response) {
        NSDictionary *dic = [response objectForKey:@"data"];
        ICGroup *group = [ICGroup mj_objectWithKeyValues:dic];
        
        if ([group.gType isEqualToString:@"0"]) {
            group.gName = [ICUser currentUser].eName;
        } else if ([group.gType isEqualToString:@"1"]) {
            for (ICUser *user in group.userList) {
                if (![user.eId isEqualToString:[ICUser currentUser].eId]) {
                    group.gName =  user.eName;
                }
            }
        }
        if ([[dic objectForKey:@"master"] isEqualToString:[ICUser currentUser].eId]) {
            group.master = 1;
        } else {
            group.master = 0;
        }
        group.valid    = 1; // 默认肯定可用
        group.busy     = 0; // 默认是0，不免打扰
        
        if ([group.gType isEqualToString:@"1"]) {
            // 保存常用联系人
            for (ICUser *user in group.userList) {
                if (![user.eId isEqualToString:[ICUser currentUser].eId]) {
                    group.photoId = group.photoId; // 双人回话 头像为用户头像
                    user.photoId = group.photoId;   // 单人会话 可以这么特殊处理
                    [ICMessageDatabase saveUser:user];
                }
            }
        } else {
            NSMutableArray *groupUsers = [[NSMutableArray alloc] init];
            NSMutableArray *saveUsers = [[NSMutableArray alloc] init];
            for (ICUser *gUser in group.userList) {
                ICGroupUser * groupUser = [[ICGroupUser alloc] init];
                groupUser.eId = gUser.eId;
                groupUser.nName = gUser.nName == nil ? gUser.eName : gUser.nName;
                groupUser.valid = gUser.valid;
                [saveUsers addObject:gUser];
                [groupUsers addObject:groupUser];
//                [ICMessageDatabase saveUser:gUser];
//                [ICMessageDatabase saveGroupUserWithGroupId:group.gId groupUser:groupUser];
                // 须保存到ic_employee表中
            }
            [ICMessageDatabase saveUsers:saveUsers];
            [ICMessageDatabase saveGroupUsersWithGroupId:group.gId groupUsers:groupUsers];
        }
        
        if (![ICMessageDatabase isGroupExisted:group.gId]) {
            [ICMessageDatabase saveGroup:group];
            [ICMessageDatabase updateGroupLastMessageTime:group.gId lastMsgTime:[dic[@"lastUpdate"] integerValue] lastMsgTxt:nil lastMsgId:@"0" lastChangeId:[ICUser currentUser].eId];
        } else {
            [ICMessageDatabase changeGroupLocalType:1 GroupId:group.gId];
        }
        
        [ICMessageHelper setGroupInfoLastUpdate:[dic objectForKey:@"lastUpdate"] gId:group.gId];
        
        if (handle) {
            handle(group);
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationDidCreatedConversation object:nil];

    } Failure:^(NSError *error, id other) {
        [MBProgressHUD showError:error.domain];
    }];
}


+ (void)createOrgGroupWith:(NSDictionary *)param Handle:(CreateSuccessHandle)handle {
    [[ICSocketRequestManager sharedInstance] createOrgGroupWithObject:param Success:^(id response) {
        
        NSDictionary *dic = [response objectForKey:@"data"];
        ICGroup *group = [ICGroup mj_objectWithKeyValues:dic];
        group.valid    = 1; // 默认肯定可用
        group.busy     = 0; // 默认是0，不免打扰
        if ([group.gType isEqualToString:@"2"]) {
            if ([[dic objectForKey:@"master"] isEqualToString:[ICUser currentUser].eId]) {
                group.master = 1;
            } else {
                group.master = 0;
            }
        }
        
        // 保存组
        [ICMessageDatabase saveGroup:group];
        [ICMessageDatabase updateGroupLastMessageTime:group.gId lastMsgTime:[ICMessageHelper currentMessageTime] lastMsgTxt:nil lastMsgId:@"0" lastChangeId:[ICUser currentUser].eId];
        // 保存人员
        NSMutableArray *groupUsers = [[NSMutableArray alloc] init];
        NSMutableArray *saveUsers = [[NSMutableArray alloc] init];
        for (ICUser *gUser in group.userList) {
            ICGroupUser * groupUser = [[ICGroupUser alloc] init];
            groupUser.eId = gUser.eId;
            groupUser.nName = gUser.nName == nil ? gUser.eName : gUser.nName;
            groupUser.valid = gUser.valid;
            [saveUsers addObject:gUser];
            [groupUsers addObject:groupUser];
//            [ICMessageDatabase saveUser:gUser];
//            [ICMessageDatabase saveGroupUserWithGroupId:group.gId groupUser:groupUser];
        }
        [ICMessageDatabase saveUsers:saveUsers];
        [ICMessageDatabase saveGroupUsersWithGroupId:group.gId groupUsers:groupUsers];
        // 更新 lastUpdate
        [ICMessageHelper setGroupInfoLastUpdate:[dic objectForKey:@"lastUpdate"] gId:group.gId];
        
        if (handle) {
            handle(group);
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationDidCreatedConversation object:nil];

    } Failure:^(NSError *error, id other) {
        [MBProgressHUD showError:error.domain];
    }];
}

+ (void)createTwoGroupWith:(NSDictionary *)param Handle:(CreateSuccessHandle)handle {
   
    [[ICSocketRequestManager sharedInstance] createTwoGroupWithObject:param Success:^(id object) {
        NSDictionary *dic = [object objectForKey:@"data"];
        ICGroup *group = [ICGroup mj_objectWithKeyValues:dic];
        NSArray *userList = [[object objectForKey:@"data"] objectForKey:@"userList"];
        for (NSDictionary *dict  in userList) {
            if (![dict[@"eId"] isEqualToString:[ICUser currentUser].eId]) {
                group.gName    = dict[@"eName"];
                group.valid    = 1; // 默认肯定可用
                group.busy     = 0; // 默认是0，不免打扰
                group.photoId  = dict[@"photoId"];
                group.lastMsgTime = [ICMessageHelper currentMessageTime];
                [ICMessageDatabase saveGroup:group];
                
                ICUser *user = [[ICUser alloc] init];
                user.eId     = dict[@"eId"];
                user.eName   = dict[@"eName"];
                user.photoId = dict[@"photoId"];
                user.email = dict[@"email"];
                [ICMessageDatabase saveUser:user];
                
            }
        }
        
        [ICMessageHelper setGroupInfoLastUpdate:[dic objectForKey:@"lastUpdate"] gId:group.gId];
        
        if (handle) {
            handle(group);
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationDidCreatedConversation object:nil];
        
    } Failure:^(NSError *error, id other) {
        if (handle) {
            handle(nil);
        }
        NSLog(@"服务器返回错误信息：%@",error.domain);
//        [MBProgressHUD showError:error.domain];
    }];
}




@end
